package com.example.om_export.common.entity;

import com.github.pagehelper.Page;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回结果用的通用载体
 * @author wb-ycl473317
 */
public class Result {

    public static final String SUCCESS_MSG = "操作成功";

    public static final String FAIL_MSG = "操作失败";

    public static final String ERROR_MSG = "未知错误";

    private int code;

    private String msg;

    private Object obj;

    private Map<String,Object> other;

    private Result(int code, String msg, Object obj) {
        this.code = code;
        this.msg = msg;
        this.obj = obj;
    }

    /**
     * 根据sql返回行数生成结果
     * @param row
     * @return
     */
    public static Result byRow(int row){
        return row>0?Result.success():Result.fail();
    }

    public static Result success(Object obj){
        return new Result(200,SUCCESS_MSG,obj);
    }

    public static Result success(){
        return success(null);
    }

    public static Result fail(){
        return fail(FAIL_MSG);
    }

    public static Result fail(String msg){
        return fail(500,msg);
    }

    public static Result fail(Integer code,String msg){
        return new Result(code,msg,null);
    }

    /**
     * 根据page插件返回的结果生成
     * @param pageInfo
     * @return
     */
    public static Result byPage(Page<Object> pageInfo) {
        return Result.success(pageInfo.getResult()).addOther("total",pageInfo.getTotal());
    }

    /**
     * 错误 一般是发生了异常
     * @return
     */
    public static Result error() {
        return new Result(500,ERROR_MSG,null);
    }

    public Result addOther(String key,Object val){
        if(this.other==null){
            this.other=new HashMap<>(16);
        }
        this.other.put(key,val);
        return this;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getObj() {
        return obj;
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }

    public Map<String, Object> getOther() {
        return other;
    }

    public void setOther(Map<String, Object> other) {
        this.other = other;
    }

    public Result addOtherAll(Map<String,Object> map) {
        if(this.other==null){
            this.other=new HashMap<>(map.size());
        }
        this.other.putAll(map);
        return this;
    }
}
